<?php

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2020/11/25
 * Time: 17:18
 */
namespace app\api\controller\log;


use app\api\controller\BaseController;
use app\common\exception\CustomException;
use think\Db;
use think\Request;

class ErrorLogController extends BaseController
{
    /**
     * @name 错误日志上传
     * @author wx
     * @date 2020/11/25 17:20
     */
    public function upload(Request $request)
    {
        $data = file_get_contents('php://input','r');

        $data = json_decode($data,true);


        //数据验证
        $this->validate($data,'ErrorLog');
        //场景验证
        switch ($data['data']['source']){
            case 1:
                $scene = 'clientUpload';
                break;
            case 2:
                $scene = 'middlewareUpload';
                break;
            default:
                $scene = 'clientUpload';
        }
        $this->validate($data,'ErrorLog.'.$scene);

        //查询数据
        if(isset($data['hostkey']) && $scene == 'clientUpload'){
            $clientHostId = Db::name('host')->where('hostkey', $data['hostkey'])->value('id');

            if(!$clientHostId){
                throw new CustomException('未查询到主机信息', '202');
            }
        }

        //入库
        $type = isset($data['data']['logid']) ? 1 : 2;
        $logId = isset($data['data']['logid']) ? $data['data']['logid'] : 0;
        $hostId = $scene == 'clientUpload' ? $clientHostId : 0;
        $ip = $scene != 'clientUpload' ? $data['data']['ip'] : '';
        $insertData = [
            'source' => $data['data']['source'],
            'host_id' => $hostId,
            'log_id' => $logId,
            'type' => $type,
            'module' => $data['data']['name'],
            'error_msg' => $data['data']['message'],
            'error_time' => $data['data']['time'],
            'ctime' => time(),
            'ip' => $ip
        ];

        $id = Db::name('host_error_log')->insertGetId($insertData);
        $return['id'] = $id;

        return $this->jsonOutPut($return);
    }
}